package com.iwords.android;


import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONObject;

import com.admogo.AdMogoLayout;
import com.iwords.android.DBHelper.LearningStatus;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * iwords应用的主Activity 
 */
public class ShowWord extends Activity implements OnTouchListener {

	/**用于捕捉touch的gesture)*/
	private GestureDetector gd;	

	IWordsApp iWordsApp;
	WordsQueueManager wordsQueueManager;
	
	/**用于轮换显示单词的Views*/
	private AnimationView animationView;
	/**用于显示不同级别单词计数的Views*/
	private LevelViews levelViews;
	//private cn.appmedia.ad.BannerAdView adView;
	private AdMogoLayout adMogoLayout;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//System.out.println("ShowWord.onCreate();&&&&&&&&&&%%%%%%%%%%%");
		setContentView(R.layout.show_word);
		this.iWordsApp = ((IWordsApp) getApplicationContext());
		this.wordsQueueManager = WordsQueueManager.getInstance();
		this.wordsQueueManager.setActivity(this);
		this.animationView = new AnimationView(this);
		this.levelViews = new LevelViews(this);
		this.setTitle(this.wordsQueueManager.getCurrentLibName());
		addGestureListener();
		showDefaultWord();
		
		//如果用户没有付费，弹出广告
		if(this.iWordsApp.isNeedPay()){
			adMogoLayout = new AdMogoLayout(this,"ac20c206acf44616b4aed9a048757337"); 
			FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
					FrameLayout.LayoutParams.FILL_PARENT,
					FrameLayout.LayoutParams.WRAP_CONTENT); 
			// 设置广告出现的位置(悬浮于底部) 
			params.bottomMargin = 0;
			params.gravity = Gravity.BOTTOM;
			addContentView(adMogoLayout, params);
		}else{
			if(adMogoLayout != null){
				this.adMogoLayout.setVisibility(View.GONE);
			}
		}
//		System.out.println("ShowWord.onCreate() this.iWordsApp.isNeedPay()="+this.iWordsApp.isNeedPay());
//		if(this.iWordsApp.isNeedPay()){
//			adView = new cn.appmedia.ad.BannerAdView(this);
//			System.out.println("ShowWord.onCreate()　１ this.iWordsApp.isNeedPay()="+this.iWordsApp.isNeedPay());
//			LinearLayout layout = (LinearLayout)this.findViewById(R.id.show_word_content);
//			System.out.println("ShowWord.onCreate() ２　this.iWordsApp.isNeedPay()="+this.iWordsApp.isNeedPay());
//			layout.addView(adView);
//			System.out.println("ShowWord.onCreate() ３　this.iWordsApp.isNeedPay()="+this.iWordsApp.isNeedPay());
//		}else{
//			if(adView != null){
//				LinearLayout layout = (LinearLayout)this.findViewById(R.id.show_word_content);
//				layout.removeView(adView);
//			}
//		}
	}
	public LevelViews getLevelViews() {
		return levelViews;
	}

	public void setLevelViews(LevelViews levelViews) {
		this.levelViews = levelViews;
	}

	public int getCurrentQueueIndex() {
		return this.wordsQueueManager.getCurrentQueueIndex();
	}
	public void setCurrentQueueIndex(int currentQueueIndex) {
		//System.out.println("ShowWord.setCurrentQueueIndex() currentQueueIndex = "+currentQueueIndex);
		this.wordsQueueManager.setCurrentQueueIndex(currentQueueIndex);
		this.wordsQueueManager.loadCurrentQueue();
	}
	/**当用户点击改变单词队列，需要从服务器端获取对应队列单词*/
	void changeQueue(int levelQueueIndex){
		//首先先Hilight当前队列
        getLevelViews().highlight(levelQueueIndex);
        setCurrentQueueIndex(levelQueueIndex);        
        //System.out.println("LevelViewsListener.onClick() changeQueue(levelQueueIndex) levelQueueIndex="+levelQueueIndex);
		try{
			this.animationView.showWord(wordsQueueManager.getWord());
		}catch(NeedMoreNewWordsException e){
			this.showMoreDialog();
		}catch(Exception e){
			this.displayMessage(e.getMessage());
		}
		
	}
	//当没有词汇可以学习时，问用户是否要重新获取一批
	void showMoreDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("提示");
		builder.setMessage("您已完成今天的学习任务，还想继续学习更多吗？");
			builder.setPositiveButton("再来一批", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//System.out.println("Splash.showMigrationDialog() 再来一批");
					try{
						ShowWord.this.wordsQueueManager.newBatch();
						ShowWord.this.levelViews.refreshLevelCount();
						ShowWord.this.showDefaultWord();
					}catch(Exception e){
						ShowWord.this.displayMessage(e.getMessage());
					}
				}
			});

		Dialog dialog = builder.setNegativeButton("就这样吧", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//System.out.println("Splash.showMigrationDialog() 就这样吧");
				//IWords.this.finish();
			}
		}).create();
		//dialog.setCancelable(false);
		dialog.getWindow().setGravity(Gravity.BOTTOM);
		dialog.show();
	}
	
	/**课本刚刚加载时，默认显示默认队列的第1个单词*/
	void showDefaultWord(){
		try{
			//System.out.println("userWordLibLoaded="+iWordsApp.getUserWordLibLoaded());
			//System.out.println("ShowWord.showDefaultWord() currentLibId="+currentLibId);
			try{
				this.animationView.showWord(wordsQueueManager.getDefaultWord());//加载完数据，默认显示第一个单词
			}catch(NeedMoreNewWordsException e){
				this.showMoreDialog();
			}
			this.levelViews.refreshLevelCount();
			this.levelViews.highlight(wordsQueueManager.getCurrentQueueIndex());
			//e.printStackTrace();
		}catch(Exception e){
			this.displayMessage(e.getMessage());
		}
	}
	
	/**把touch的event传递给gestureListener处理*/
	public boolean onTouch(View v, MotionEvent event) {
		//System.out.println("ShowWord.onTouch() v="+v+" event="+event);
		return gd.onTouchEvent(event);
	}
	
	/**添加手指滑动事件监听*/
	private void addGestureListener(){
		//创建GestureDetector实例，重写其onFling()方法，处理手指滑动事件	
		 gd = new GestureDetector (this, new GDetector()); 
		findViewById(R.id.show_word_content).setOnTouchListener(this);
		//findViewById(R.id.animation_layout).setOnTouchListener(this);//doesn't work
		//findViewById(R.id.animation_layout2).setOnTouchListener(this);//doesn't work
		//findViewById(R.id.word_layout).setOnTouchListener(this);//doesn't work
		//findViewById(R.id.word_layout2).setOnTouchListener(this);//doesn't work
		//findViewById(R.id.sentences).setOnTouchListener(this);
		//findViewById(R.id.sentences2).setOnTouchListener(this);
		findViewById(R.id.sentences_scroll).setOnTouchListener(this);
		findViewById(R.id.sentences2_scroll).setOnTouchListener(this);
		//findViewById(R.id.animation_frame).setOnTouchListener(this);//doesn't work
		
		//这里如果没有 implements OnTouchListener 会报错		
		findViewById(R.id.show_word_content).setLongClickable(true);//不加这个滑动就没反应	
	}
	
	class GDetector extends SimpleOnGestureListener {	//GDetector 名字是随便起的	
		@Override
		public boolean onFling(	MotionEvent e1,  	//按下时的状态,位置
							MotionEvent e2, 	//松手时的状态，位置
							float vx,			//x坐标的移动速度，单位: px/秒
							float vy){			//y坐标的移动速度
			if((e1.getX()-e2.getX()>60) && (Math.abs(vx)>50)) {	//滑动速度足够快至少50点/秒，手指起落点减起点是正值且>200 判断属于向左滑动
				//tv_log.setText("Fling to Left.\n"+tv_log.getText());	//debug.输出到 tv_log
				//System.out.println("向左滑动。");
				flingLeft();
			}else if ((e2.getX()-e1.getX()>60) && (Math.abs(vx)>50)) { //同理判断是向右滑动
				//tv_log.setText("Fling to Right.\n"+tv_log.getText()); 	//debug
				//System.out.println("向右滑动。");
				flingRight();
			}else if ((e1.getY()-e2.getY()>60) && (Math.abs(vy)>50)) { //同理判断是向右滑动
				//tv_log.setText("Fling to Right.\n"+tv_log.getText()); 	//debug
				//System.out.println("向上滑动。");
				flingUp();
			}else if ((e2.getY()-e1.getY()>60) && (Math.abs(vy)>50)) { //同理判断是向右滑动
				//tv_log.setText("Fling to Right.\n"+tv_log.getText()); 	//debug
				//System.out.println("向下滑动。");
				flingDown();
			}
			return true;
		}
	}	
	

	private void flingUp(){
		animationView.animate(AnimationDirection.Up, wordsQueueManager.flingUp());
		this.levelViews.refreshLevelCount();
	}
	private void flingDown(){
		animationView.animate(AnimationDirection.Down, wordsQueueManager.flingDown());
		this.levelViews.refreshLevelCount();
	}
	private void flingLeft(){
		animationView.animate(AnimationDirection.Left, wordsQueueManager.flingLeft());
		this.levelViews.refreshLevelCount();
		if(wordsQueueManager.getCurrentQueueIndex()==6 && wordsQueueManager.getCurrentQueue().size()==0){//新词
			this.showMoreDialog();
		}
	}
	private void flingRight(){
		animationView.animate(AnimationDirection.Right, wordsQueueManager.flingRight());
		this.levelViews.refreshLevelCount();
		if(wordsQueueManager.getCurrentQueueIndex()==6 && wordsQueueManager.getCurrentQueue().size()==0){//新词
			this.showMoreDialog();
		}
	}
	
	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Group ID 
		int groupId = 0; 
		// The order position of the item 
		int menuItemOrder = Menu.NONE; 
		// Create the menu item and keep a reference to it. 
		
		MenuItem menuItem = menu.add(groupId, R.integer.menu_item_first, menuItemOrder, this.getString(R.string.menu_item_lib_select));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_lib_select));
		
		menuItem = menu.add(groupId, R.integer.menu_item_fifth, menuItemOrder, this.getString(R.string.menu_item_words_list));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_words_list));
		menuItem = menu.add(groupId, R.integer.menu_item_second, menuItemOrder, this.getString(R.string.menu_item_settings));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_settings));
		menuItem = menu.add(groupId, R.integer.menu_item_fourth, menuItemOrder, this.getString(R.string.menu_item_advice));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_feedback));
		menuItem = menu.add(groupId, R.integer.menu_item_sixth, menuItemOrder, this.getString(R.string.menu_item_help));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_profile));
		menuItem = menu.add(groupId, R.integer.menu_item_third, menuItemOrder, this.getString(R.string.menu_item_logout));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_logout));
		return true;
	}
	
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}
	@Override 
	public boolean onOptionsItemSelected(MenuItem item)	{
		this.vibrate();
		if (item.getItemId() == R.integer.menu_item_first) {
			//System.out.println("选择词库");
	    	Intent intent = new Intent(this, ShowWordLib.class);
	    	intent.putExtra("currentWordLibId", wordsQueueManager.getCurrentLibId());
	    	startActivity(intent);
	    	this.finish();
		} else if(item.getItemId() == R.integer.menu_item_second)	{
			//System.out.println("设置");
			Intent intent = new Intent(this, UserSettings.class);
			this.startActivity(intent);
		} else if(item.getItemId() == R.integer.menu_item_third)	{
			SharedPreferences settings = this.getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();  
			editor.putBoolean("autoLogin", false);
			editor.commit();  
			this.finish();
		} else if(item.getItemId() == R.integer.menu_item_fourth)	{
			//System.out.println("提意见");
			Intent intent = new Intent(this, FeedBack.class);
			this.startActivity(intent);
		} else if(item.getItemId() == R.integer.menu_item_fifth)	{
			//System.out.println("查看队列");
			Intent intent = new Intent(this, WordsList.class);
			this.startActivity(intent);
		} else if(item.getItemId() == R.integer.menu_item_sixth)	{
			//System.out.println("帮助");
			Intent intent = new Intent(this, GuideShowWord.class);
			intent.putExtra("fromShowWordMenu", true);
			this.startActivity(intent);
		}
		
		return true;	
	}
	
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG);
		t1.show();
	}
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
		//启动线程，将客户端学习状态记录到服务器上
		new Thread(new Runnable(){
			public void run(){
				persistToServer();
			}
		}).start();
	}
	
	//将客户端尚未保存到服务器端的学习状态信息，保存到服务器端
	//1. outid 为0的 insert
	//2. outid 有值的 update
	private void persistToServer(){
		DBHelper dbHelper = new DBHelper(this);
		long userid = iWordsApp.getUser().getUserid();
		try{
			List<LearningStatus> newStatus = dbHelper.findNewStatus(userid);
			//System.out.println("ShowWord.persistToServer() newStatus.size() = "+newStatus.size());
			for(LearningStatus status : newStatus){
				//System.out.println("ShowWord.persistToServer() status.id = "+status.id);
				//System.out.println("ShowWord.persistToServer() status.outid = "+status.outid);
				//System.out.println("ShowWord.persistToServer() status.userid = "+status.userid);
				//System.out.println("ShowWord.persistToServer() status.libid = "+status.libid);
				//System.out.println("ShowWord.persistToServer() status.wordid = "+status.wordid);
				//System.out.println("ShowWord.persistToServer() status.familiarity = "+status.familiarity);
				//一个个更新到Server
				if(status.outid == 0){
					Long outid = insert(status);
					if(outid!=-1){
						status.outid = outid;
						status.persisted = 1;
						dbHelper.update(status);
					}
				}else{
					if(update(status)){
						status.persisted = 1;
						dbHelper.update(status);
					}
				}
			}
		}finally{
			dbHelper.cleanup();
		}
	}
	
	private Long insert(LearningStatus status){
		String href = this.getResources().getString(R.string.insert_status);
		href += "&userid="+status.userid;
		href += "&libid="+status.libid;
		href += "&wordid="+status.wordid;
		href += "&familiarity="+status.familiarity;
		
		HttpPost request = new HttpPost(href);
		//System.out.println("ShowWord.insert()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				JSONObject defaultValue = (JSONObject) jSONObject.getJSONObject("defaultValue");
				if(defaultValue.has("outid")){
					return  defaultValue.getLong("outid");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return -1L;
	}
	
	private boolean update(LearningStatus status){
		String href = this.getResources().getString(R.string.update_status);
		href += "&outid="+status.outid;
		href += "&familiarity="+status.familiarity;
		
		HttpPost request = new HttpPost(href);
		//System.out.println("ShowWord.update()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			return jSONObject.getBoolean("isSuccess");
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

}